package com.gzy.wb.security;

import com.gzy.wb.model.User;
import com.gzy.wb.server.AuthServer;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.UserDetailsManagerConfigurer;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JWTFilter extends BasicAuthenticationFilter {
    private AuthenticationManager authenticationManager;
    private AuthServer authServer;

    public JWTFilter(AuthenticationManager authenticationManager, AuthServer authServer) {
        super(authenticationManager);

        this.authenticationManager = authenticationManager;
        this.authServer = authServer;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        String token = request.getHeader("Token");
        if (StringUtils.isEmpty(token)){
            chain.doFilter(request, response);
            return;
        }


        User user = authServer.checkJWT(token);
        UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .roles(user.getRole())
                .build();

        // 通过验证
        UsernamePasswordAuthenticationToken uptoken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(uptoken);
        chain.doFilter(request, response);
    }
}
